package com.steven.im.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.steven.putorefresh.BaseBothListener;
import com.steven.putorefresh.PullToBothLayout;
import com.steven.im.R;
import com.steven.im.adapter.MyorderAdapter;
import com.steven.im.base.Constant;
import com.steven.im.base.LazyLoadBaseFragment;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.MyorderEntity;
import com.steven.im.entity.PageEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.ConfirmOrderActivity;
import com.steven.im.ui.activity.ShoworderActivity;
import com.steven.im.utils.GsonUtils;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

/**
 * 我的订单
 * A simple {@link Fragment} subclass.
 * Use the {@link MyorderFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyorderFragment extends LazyLoadBaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private boolean isFirstVisible = false;

    PullToBothLayout pullToBothLayout;
    private boolean isRefresh = false;//是否是下拉刷新
    private boolean isLoadMore = false;//是否是 上拉加载
    int totalPage = 0;//总页数

    //我的订单列表
    RecyclerView rvMyorder;
    List<MyorderEntity> mList = new ArrayList<>();
    MyorderAdapter mAdapter;

    int pageNo = 1;//当前页数


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public MyorderFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MyorderFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MyorderFragment newInstance(String param1, String param2) {
        MyorderFragment fragment = new MyorderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_myorder;
    }

    @Override
    protected void initView(View rootView) {
        Logger.i(mParam1 + "initView");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getActivity());
        if (rvMyorder == null) {
            rvMyorder = rootView.findViewById(R.id.rv_myorder);
        }
        if (pullToBothLayout == null) {
            pullToBothLayout = rootView.findViewById(R.id.pullRefreshBoth);
        }
        rvMyorder.setLayoutManager(linearLayoutManager);
        mAdapter = new MyorderAdapter(mList, getActivity(), mParam2);
        rvMyorder.setAdapter(mAdapter);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (ScreenUtil.isFastClick()) {
                    return;
                }
                if ("0".equals(mList.get(position).getStatus())) {//待支付
                    startActivity(new Intent(getActivity(), ConfirmOrderActivity.class)
                            .putExtra("my_type", "order")
                            .putExtra("Id", mList.get(position).getOrderId())
                            .putExtra("salesType", mList.get(position).getType()));
                } else if ("20".equals(mList.get(position).getStatus())) {//签收
                    orderReceipt(mList.get(position).getOrderId());
                } else if ("30".equals(mList.get(position).getStatus())) {//晒单
                    startActivity(new Intent(getActivity(), ShoworderActivity.class)
                            .putExtra("orderId", mList.get(position).getOrderId()));
                }
            }
        });

        setListener();
    }

    /**
     * 事件监听
     */
    private void setListener() {
        pullToBothLayout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                isRefresh = true;
                pageNo = 1;
                refreshData();
            }

            @Override
            public void loadMore() {
                if (pageNo < totalPage) {
                    isLoadMore = true;
                    pageNo++;
                    refreshData();
                } else {
                    ToastUtil.showShort(getActivity(), "数据加载完毕");
                    pullToBothLayout.finishLoadMore();
                }
            }
        });
    }

    @Override
    protected void requestData() {
        super.requestData();
        requestDataAutoRefresh();
    }

    @Override
    protected void requestDataAutoRefresh() {
        super.requestDataAutoRefresh();
        Task.getApiService().getOrderList(String.valueOf(pageNo), Constant.CommonInfo.PAGE_SIZE, mParam2).enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            public void onSuccess(Response<BaseEntity> response) {
                try {
                    pullToBothLayout.finishRefresh();
                    pullToBothLayout.finishLoadMore();

                    if ("0".equals(response.body().getCode())) {
                        List<MyorderEntity> myOrderList = GsonUtils.jsonToArrayList(
                                response.body().getResult().getJSONArray("orderList").toString(),
                                MyorderEntity.class
                        );
                        if (myOrderList != null) {
                            if (isRefresh) {
                                isRefresh = false;
                                mList.clear();
                            } else if (isLoadMore) {
                                isLoadMore = false;
                            } else {
                                mList.clear();
                            }
                            mList.addAll(myOrderList);
                            mAdapter.setNewData(mList);
                        }

                        //分页
                        PageEntity pageEntity = GsonUtils.parseJSON(response.body().getResult()
                                .getJSONObject("pager").toString(), PageEntity.class);
                        if (pageEntity != null) {
                            totalPage = Integer.valueOf(pageEntity.getTotalPage());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t) {

                pullToBothLayout.finishRefresh();
                pullToBothLayout.finishLoadMore();
            }
        });
    }

    /**
     * 确认收货
     */
    private void orderReceipt(String orderId) {
        Task.getApiService().orderReceipt(orderId).enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    ToastUtil.showShort(getActivity(), response.body().getMessage());
                    refreshData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        requestDataAutoRefresh();
    }

}
